import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { CartItemDto } from '../api/divide/cart/types.gen';

interface CartStore {
  // 购物车商品列表
  cartItems: CartItemDto[];
  // 购物车商品总数
  cartItemCount: number;
  // 选中的商品列表（用于结算）
  selectedItems: CartItemDto[];
  // 选中的商品总价
  selectedTotalPrice: number;
  // 选中的商品总数
  selectedItemCount: number;
  
  // 设置购物车数据
  setCartItems: (items: CartItemDto[]) => void;
  setCartItemCount: (count: number) => void;
  setSelectedItems: (items: CartItemDto[]) => void;
  
  // 计算选中商品的总价
  calculateSelectedTotal: () => void;
  
  // 清空本地状态
  clearLocalCart: () => void;
}

// 购物车状态存储
export const useCartStore = create<CartStore>()(
  persist(
    (set, get) => ({
      cartItems: [],
      cartItemCount: 0,
      selectedItems: [],
      selectedTotalPrice: 0,
      selectedItemCount: 0,
      
      setCartItems: (items) => set({ cartItems: items }),
      setCartItemCount: (count) => set({ cartItemCount: count }),
      setSelectedItems: (items) => set({ selectedItems: items }),
      
      calculateSelectedTotal: () => {
        const { selectedItems } = get();
        const totalPrice = selectedItems.reduce((sum, item) => sum + (item.coursePrice || 0) * (item.quantity || 1), 0);
        const totalCount = selectedItems.reduce((sum, item) => sum + (item.quantity || 1), 0);
        set({ selectedTotalPrice: totalPrice, selectedItemCount: totalCount });
      },
      
      clearLocalCart: () => set({
        cartItems: [],
        cartItemCount: 0,
        selectedItems: [],
        selectedTotalPrice: 0,
        selectedItemCount: 0
      })
    }),
    {
      name: 'cart-store',
      partialize: (state) => ({
        cartItems: state.cartItems,
        cartItemCount: state.cartItemCount,
        selectedItems: state.selectedItems,
        selectedTotalPrice: state.selectedTotalPrice,
        selectedItemCount: state.selectedItemCount
      })
    }
  )
);